package com.qfedu.java1234.common.security;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qfedu.java1234.entity.bo.Menu;
import com.qfedu.java1234.entity.bo.Role;
import com.qfedu.java1234.entity.bo.SysUser;
import com.qfedu.java1234.entity.vo.ResultVO;
import com.qfedu.java1234.service.MenuService;
import com.qfedu.java1234.service.RoleService;
import com.qfedu.java1234.service.UserService;
import com.qfedu.java1234.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName LoginSuccessHandler
 * @Author ykx
 * @Date 2024/4/21 20:39
 * @Version 1.0
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        String username = authentication.getName();

        SysUser currentUser = userService.getByUsername(username);
        String token = JwtUtils.genJwtToken(username);

        // 根据用户id获取所有的角色
        List<Role> roleList = roleService.list(new QueryWrapper<Role>().inSql("id", "SELECT role_id FROM sys_user_role WHERE user_id=" + currentUser.getId()));

        // 遍历角色，获取所有菜单权限
        Set<Menu> menuSet = new HashSet<>();
        for (Role sysRole : roleList) {
            List<Menu> sysMenuList = menuService.list(new QueryWrapper<Menu>().inSql("id", "SELECT menu_id FROM sys_role_menu WHERE role_id=" + sysRole.getId()));
            menuSet.addAll(sysMenuList);
        }

        currentUser.setRoles(roleList.stream().map(Role::getName).collect(Collectors.joining(",")));

        List<Menu> sysMenuList = new ArrayList<>(menuSet);

        // 排序
        sysMenuList.sort(Comparator.comparing(Menu::getOrderNum));

        List<Menu> menuList = menuService.buildTreeMenu(sysMenuList);

        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("currentUser", currentUser);
        map.put("menuList", menuList);

        outputStream.write(JSONUtil.toJsonStr(ResultVO.success(map)).getBytes());
        outputStream.flush();
        outputStream.close();

    }
}
